<script setup lang="ts">
import { Delete, Edit } from '@element-plus/icons-vue'
import type { Action } from 'element-plus'
import { FormModal, SearchForm } from './components'
import type { KPIType } from './type'
import {
  defaultFormData,
  defaultPagingParams,
} from './index'
import { PAGING } from '@/constant'
import type { TableColumn } from '@/types'
// ------------------use------------------
// #region
const { globalProperties, $confirm, $message }
  = useCurrentInstance()
const { withLoading, loading } = useDefineLoading()
const [tableData, setTableData] = useState<any[]>([])
const [formData, setFormData] = useState<any>({
  ...defaultFormData,
})
const [pagingParams, setPagingParams] = useState<any>({
  ...defaultPagingParams,
})
const [total, setTotal] = useState<number>(0)
const [formModalTitle, setFormModalTitle]
  = useState<string>('')
const [isEdit, setIsEdit] = useState<boolean>(false)
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<Required<KPIType>>[] = [
  {
    key: uuid(),
    type: 'index',
    width: '80',
    label: '序号',
  },
  {
    key: uuid(),
    label: '班组',
    prop: 'team',
  },
  {
    key: uuid(),
    label: '日期',
    prop: 'time',
  },
  {
    key: uuid(),
    label: '考核制',
    render() {
      return '考核制'
    },
  },
  {
    key: uuid(),
    label: '当前值',
    prop: 'currentValue',
    render({ row: { currentValue } }) {
      return `${currentValue}%`
    },
  },
]
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const modalRef = ref<InstanceType<typeof FormModal>>()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region
// #endregion
// ------------------生命周期------------------
// #region
onMounted(() => {
  getTableData()
})
// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
async function deleteData(id: string) {
  const res: Action = await $confirm(
    '该操作将永久删除该数据，确定删除？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  globalProperties.$message.success(
    `${id ?? ''}删除成功！`,
  )
  getTableData()
}
async function showEditDialog(row: any) {
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('编辑')
  setIsEdit(true)
  setFormData({ ...defaultFormData, ...row })
}
async function showAddDialog() {
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('新增')
  setIsEdit(false)
  setFormData({ ...defaultFormData })
}
async function getTableData() {
  await withLoading(sleep)(1000)
  const list: KPIType[] = []
  Array.from({ length: 30 }).fill(0).forEach(() => {
    const o: KPIType = {
      id: uuid(),
      team: 'A班组',
      time: '2024-12-12',
      assessment: '',
      currentValue: Math.ceil(Math.random() * 40 + 50),
    }
    list.push(o)
  })
  setTotal(30)
  setTableData(list)
}
async function addOrUpdateData(row: any) {
  await sleep(1000)
  getTableData()
  globalProperties.$message.success(
    `${row.id ?? ''}数据更新成功！`,
  )
}
function addData() {
  addOrUpdateData(formData.value)
  modalRef.value?.close()
  $message.success('保存成功！')
}
function editData() {
  addOrUpdateData(formData.value)
  modalRef.value?.close()
  $message.success('保存成功！')
}
function handleSaveSuccess() {
  isEdit.value ? editData() : addData()
}
/** 重置 */
function reset() {
  setPagingParams({ ...defaultPagingParams })
  getTableData()
}
function search() {
  getTableData()
  Object.assign(pagingParams.value, PAGING.PARAMS)
}

// #endregion
</script>

<template>
  <div
    class="padding-sm flex-direction flex align-end container"
  >
    <view-table
      :loading="loading"
      :columns="columns"
      :data="tableData"
    >
      <template #actions>
        <SearchForm
          @search="search"
          @reset="reset"
          @plus="showAddDialog"
        />
      </template>
      <template #operate="{ row }">
        <TdButton
          title="编辑"
          :icon="Edit"
          type="primary"
          @click="showEditDialog(row)"
        />
        <TdButton
          title="删除"
          :icon="Delete"
          type="danger"
          @click="deleteData(row.id)"
        />
      </template>
    </view-table>

    <!-- 分页 -->
    <ListsPagination
      v-model:page-num="pagingParams.pageNumber"
      v-model:page-size="pagingParams.pageSize"
      :total="total"
      @current-change="getTableData"
      @size-change="getTableData"
    />
    <FormModal
      ref="modalRef"
      :title="formModalTitle"
      :data="formData"
      @save-success="handleSaveSuccess"
    />
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
